package com.pan.concurrency.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  了解下 wait 设置时间
 *
 *  解决死锁问题
 * </p>
 *
 * @author kaiji
 * @since 2020/1/25 17:22
 */
public class WaitTimeAndNotify {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        WaitTimeProducer newProducer = new WaitTimeProducer(list, "生产者-开机");

        WaitTimeConsumer c1 = new WaitTimeConsumer(list);
        WaitTimeConsumer c2 = new WaitTimeConsumer(list);

        newProducer.start();
        c1.start();
        c2.start();
    }
}

class WaitTimeProducer extends Thread {
    // 最大的list大小
    private static final int MAX = 1;
    private List<Integer> list;
    private String username;

    protected WaitTimeProducer(List<Integer> list, String username) {
        this.list = list;
        this.username = username;
    }

    @Override
    public void run() {
        int i = 1;
        while (true) {
            try {
                synchronized (list) {
                    if (list.size() >= MAX) {
                        // 单位毫秒
                        list.wait(10);
                    } else {
                        list.add(i);
                        System.out.println(username + ": 开始生产，编号为：" + i);
                        i++;
                        list.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}

class WaitTimeConsumer extends Thread {

    private List<Integer> list;

    WaitTimeConsumer(List<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            try {
                synchronized (list) {
                    if (list.isEmpty()) {
                        list.wait(10);
                    } else {
                        Integer consumerNo = list.remove(0);
                        System.out.println("消费者编号：" + consumerNo);
                        list.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}